gapi.hangout.onApiReady.add(apReady);

function apReady() {
    ko.bindingHandlers.editableText = {
        init: function (element, valueAccessor) {
            $(element).on('blur', function () {
                var observable = valueAccessor();
                observable($(this).text());
                var timeToSearch = $(this).attr("data-time");
                var arrayOfSendingResult = viewModel.messages().filter(function (cur_elem) {
                    return cur_elem.time == timeToSearch
                });
                var appObj = {
                    message_obj: {
                        userName: arrayOfSendingResult[0].userName,
                        message: arrayOfSendingResult[0].message(),
                        time: arrayOfSendingResult[0].time,
                        imagePath: arrayOfSendingResult[0].imagePath,
                        isCurrent: arrayOfSendingResult[0].userName == currentParticipant.person.displayName
                    }, update: true
                }
                translate(arrayOfSendingResult[0]);
                gapi.hangout.data.sendMessage(JSON.stringify(appObj));
            });
        },
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());
            $(element).text(value);



        }
    };

    var MessageModel = function (messages) {
        var self = this;
        self.messages = ko.observableArray(messages);

        self.addMessage = function (obj) {
            self.messages.push({
                userName: obj.userName,
                message: ko.observable(obj.message),
                time: obj.time,
                imagePath: obj.imagePath,
                isCurrent: obj.isCurrent,
                translation: ko.observable("")
            });
            var objDiv = document.getElementById("container");
            objDiv.scrollTop = objDiv.scrollHeight;

            var result = viewModel.messages().filter(function (cur_elem) {
                return cur_elem.time == obj.time;
            });

            translate(result[0]);
        }
    };

    var viewModel = new MessageModel();
    ko.applyBindings(viewModel);

    var recognition = new webkitSpeechRecognition();
    recognition.lang = "en-US";
    recognition.continuous = true;
    recognition.onresult = function (event) {
        var res;
        for (var i = event.resultIndex; i < event.results.length; ++i) {
            if (event.results[i].isFinal) {
                res = event.results[i][0].transcript;
            }
        };

        var messageObj = {
            userName: currentParticipant.person.displayName,
            message: res,
            time: new Date(),
            imagePath: currentParticipant.person.image.url,
            isCurrent: false
        };

        var appObj = {
            message_obj: messageObj,
            update: false
        }

        gapi.hangout.data.sendMessage(JSON.stringify(appObj));
        messageObj.isCurrent = true;
        viewModel.addMessage(JSON.parse(JSON.stringify(messageObj)));
    };


    var currentParticipant = gapi.hangout.getLocalParticipant();
    gapi.hangout.av.onMicrophoneMute.add(microMuteEvent);
    gapi.hangout.data.onMessageReceived.add(messageRecievedEvent);

    $("#generateButton").click(generateJediFile);
    $("#translateLang").change(langChanged);

    function microMuteEvent(e) {

        if (e.isMicrophoneMute) {
            recognition.stop();
        }
        else {
            recognition.start();
        }
    }

    function messageRecievedEvent(e) {
        var obj = JSON.parse(e.message);
        if (obj.update) {
            var result = viewModel.messages().filter(function (cur_elem) {
                return cur_elem.time == obj.message_obj.time;
            });
            if (result.length > 0) {
                result[0].message(obj.message_obj.message);
                translate(result[0]);
            }
        }
        else {
            viewModel.addMessage(obj.message_obj);
        }
    }

    function translate(obj) {
        var lang = $("#translateLang").find('option:selected').text();
        if (lang && obj) {
            var tooltipText = translate_bing(obj.message(), lang.toLowerCase(), obj);
        }
    }

    function generateJediFile(){
        var arrayRes = viewModel.messages();
        var result = new Array;

        for (var i = 0; i < arrayRes.length; i++) {
            result.push({
                userName: arrayRes[i].userName,
                message: arrayRes[i].message(),
                time: arrayRes[i].time
            });
        }
        var output = JSON.stringify(result);
        window.open().document.write(output);
    }
    function langChanged(){
        
        var lang = $(this).find('option:selected').text();

        if (lang) {
            var allEntries = viewModel.messages();

            for (var i = 0; i < allEntries.length; i++) {
                var tooltipText = translate_bing(allEntries[i].message(), lang.toLowerCase(), allEntries[i]);
            }
        }
    }

    function translate_bing(text, lang, updateElem) {

        jQuery.ajax({
            url: 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20150301T032824Z.68843095b3a67505.62cbf0e7ed44e1641da20541477f09185fe21156&text='+text +'&lang=en-'+ lang,
            success: function (response) {
                updateElem.translation(response.text[0]);
            }
        });
    }
}
/*
function clickStopButton(){
  

}




$(document).ready(buildApp);


function buildApp(){
  buildDom();
}




function buildDom()
{
  var supportedLangs = ['en-GB','en-US','ru-RU'];


  var innerDom = '<div id="mainDiv"><select id="select_speech_lang" data-bind="options: lang"></select><select id="select_translate_lang"></select></div>';
  var wrapper = $('#contentWrapper');
  wrapper.html(innerDom);
  for(var i =0;i<supportedLangs.length;i++)
    select_speech_lang.options[i] = new Option(supportedLangs[i],supportedLangs[i]);
  for(var i =0;i<supportedLangs.length;i++)
    select_translate_lang.options[i] = new Option(supportedLangs[i],supportedLangs[i]);
  $(select_speech_lang).change(speechLangChanged);
  $(select_translate_lang).change(speechTranslateChanged);
}

function speechLangChanged()
{

}

function speechTranslateChanged()
{
  
}






console.log('hello');

var recognition = new webkitSpeechRecognition();
recognition.lang = "en-GB";

recognition.continuous = true;
recognition.onresult = function(event) { 
  console.log(event); 
  var res = event.results[0][0].transcript;
  var elem = document.getElementById('div123');
  elem.innerText = res;
}
recognition.onstart = function(event) { 
  console.log('start'); 
}

console.log('hello');
*/